﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Xml.Linq;
using HotelSoftBusLib;

namespace HotelSoftBusWeb
{
    /// <summary>
    /// DeviceService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class DeviceService : System.Web.Services.WebService
    {
        public DeviceService()
        {
            //如果使用设计的组件，请取消注释以下行
            //InitializeComponent();
        }
        /// <summary>
        /// 返回消息对象
        /// </summary>
        SocketReturnMsg retMsg = new SocketReturnMsg();
        /// <summary>
        /// 接收数据
        /// </summary>
        Room room = new Room();
        Customer customer = new Customer();
        Operators operators = new Operators();
        public string socketIp = string.Empty;
        public string socketPort = string.Empty;
        /// <summary>
        /// 客人入住
        /// 打卡空调和灯光
        /// </summary>
        /// <param name="customerInfo">客人信息</param>
        /// <param name="roomInfo">房间信息</param>
        /// <param name="operTime">操作时间</param>
        /// <param name="operName">操作人员</param>
        /// <returns></returns>
        [WebMethod(Description = "客人入住")]
        public string CheckIn(string customerInfo, string roomInfo, string operTime, string operName)
        {
            Socket client = null;
            retMsg = new SocketReturnMsg();
            customer = null;
            room = null;
            operators = null;
            WriteLogRecord("System", LogRecordTypeEnum.Business, "酒馆软件调用总线WebService，客人入住");
            bool iscomplete = IsReceivedInfoComplete(customerInfo, roomInfo, operTime, operName);
            if (iscomplete)
            {
                if (GetSocketIpAndPort())
                {
                    IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(socketIp), int.Parse(socketPort));
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        client.Connect(ipe);
                    }
                    catch (Exception ex)
                    {
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接错误");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接错误," + ex.Message;
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    if (!client.Connected)
                    {

                        //连接失败
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接失败");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接失败";
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    SocketCommdMsg msg = new SocketCommdMsg();
                    msg.MsgType = "CheckIn";
                    msg.CustomerInfo = customer;
                    msg.RoomInfo = room;
                    string DataStr = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                    byte[] data = Encoding.GetEncoding("GB2312").GetBytes(DataStr);
                    client.Send(data, data.Length, SocketFlags.None);
                    byte[] arr = new byte[2048];
                    int s = client.Receive(arr);
                    string recieveMsg = Encoding.Default.GetString(arr).TrimEnd('\0');
                    arr = new byte[2048];
                    disposeSocket(client);
                    return recieveMsg;
                }
                else
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                }
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
            }
        }

        /// <summary>
        /// 客人退房
        /// 关闭空调和灯光
        /// </summary>
        /// <param name="customerInfo">客人信息</param>
        /// <param name="roomInfo">房间信息</param>
        /// <param name="operTime">操作时间</param>
        /// <param name="operName">操作人员</param>
        /// <returns></returns>
        [WebMethod(Description = "客人退房")]
        public string CheckOut(string customerInfo, string roomInfo, string operTime, string operName)
        {
            Socket client = null;
            retMsg = new SocketReturnMsg();
            customer = null;
            room = null;
            operators = null;
            WriteLogRecord("System", LogRecordTypeEnum.Business, "酒馆软件调用总线WebService,客人退房");
            bool iscomplete = IsReceivedInfoComplete(customerInfo, roomInfo, operTime, operName);
            if (iscomplete)
            {
                if (GetSocketIpAndPort())
                {
                    IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(socketIp), int.Parse(socketPort));
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        client.Connect(ipe);
                    }
                    catch (Exception ex)
                    {
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接失败");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接失败," + ex.Message;
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    if (!client.Connected)
                    {

                        //连接失败
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接错误");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接错误";
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    SocketCommdMsg msg = new SocketCommdMsg();
                    msg.MsgType = "CheckOut";
                    msg.CustomerInfo = customer;
                    msg.RoomInfo = room;
                    string DataStr = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                    byte[] data = Encoding.GetEncoding("GB2312").GetBytes(DataStr);
                    client.Send(data, data.Length, SocketFlags.None);
                    byte[] arr = new byte[2048];
                    int s = client.Receive(arr);
                    string recieveMsg = Encoding.Default.GetString(arr).TrimEnd('\0');
                    arr = new byte[2048];
                    disposeSocket(client);
                    return recieveMsg;
                }
                else
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                }
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
            }
        }
        /// <summary>
        /// 制作VIPCard的接口
        /// </summary>
        /// <param name="customerInfo">客人信息</param>
        /// <param name="operTime">操作时间</param>
        /// <param name="operName">操作人员</param>
        /// <returns></returns>
        [WebMethod(Description = "制作VIPCard")]
        public string MakeVIPCard(string customerInfo, string operTime, string operName)
        {
            Socket client = null;
            retMsg = new SocketReturnMsg();
            customer = null;
            room = null;
            operators = null;
            WriteLogRecord("System", LogRecordTypeEnum.Business, "酒馆软件调用总线WebService，制作VIPCard");
            bool iscomplete = IsReceivedInfoComplete(customerInfo, "MakeVIPCard", operTime, operName);
            if (iscomplete)
            {
                if (GetSocketIpAndPort())
                {
                    IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(socketIp), int.Parse(socketPort));
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        client.Connect(ipe);
                    }
                    catch (Exception ex)
                    {
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接错误");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接错误," + ex.Message;
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    if (!client.Connected)
                    {

                        //连接失败
                        WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "Socket通讯连接失败");
                        retMsg.IsSuccess = false;
                        retMsg.Status = "-1006";
                        retMsg.Message = "Socket通讯连接失败";
                        return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                    }
                    SocketCommdMsg msg = new SocketCommdMsg();
                    msg.MsgType = "MakeVIPCard";
                    msg.CustomerInfo = customer;
                    msg.RoomInfo = null;
                    string DataStr = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                    byte[] data = Encoding.GetEncoding("GB2312").GetBytes(DataStr);
                    client.Send(data, data.Length, SocketFlags.None);
                    byte[] arr = new byte[2048];
                    int s = client.Receive(arr);
                    string recieveMsg = Encoding.Default.GetString(arr).TrimEnd('\0');
                    arr = new byte[2048];
                    disposeSocket(client);
                    return recieveMsg;
                }
                else
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
                }
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(retMsg);
            }
        }

        /// <summary>
        /// 制卡设备客户端登记到服务器。
        /// 制卡设备先服务器端登记自己的IP地址和设备类型。
        /// </summary>
        /// <param name="customerInfo"></param>
        /// <param name="roomInfo"></param>
        /// <param name="operName"></param>
        /// <returns></returns>
        [WebMethod(Description = "制卡设备客户端登记到服务器")]
        public string DeviceRegister(string customerInfo, string roomInfo, string operName)
        {
            return "true";
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="operName"></param>
        /// <param name="logRecordTypeEnum"></param>
        /// <param name="logMsg"></param>
        /// <param name="conn"></param>
        public void WriteLogRecord(string operName, LogRecordTypeEnum logRecordTypeEnum, string logMsg)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionStr"].ToString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(string.Format("INSERT INTO [HotelsoftBus].[dbo].[Log]([OperName],[OperTime],[LogType],[Description]) VALUES ('" + operName + "','" + System.DateTime.Now + "','" + logRecordTypeEnum + "','" + logMsg + "')"), conn))
                {
                    cmd.ExecuteNonQuery();
                }
                conn.Close();
            }
        }

        /// <summary>
        /// 判断接收到的信息是否完整
        /// </summary>
        /// <param name="customerInfo"></param>
        /// <param name="roomInfo"></param>
        /// <param name="operTime"></param>
        /// <param name="operName"></param>
        /// <returns></returns>
        public bool IsReceivedInfoComplete(string customerInfo, string roomInfo, string operTime, string operName)
        {
            if (string.IsNullOrEmpty(operName))
            {
                WriteLogRecord("System", LogRecordTypeEnum.Business, "传入操作人员信息为空");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1001";
                retMsg.Message = "传入操作人员信息格式错误";
                return false;
            }
            try
            {
                operators = Newtonsoft.Json.JsonConvert.DeserializeObject<Operators>(operName.Trim());
            }
            catch (Exception ex)
            {
                WriteLogRecord("System", LogRecordTypeEnum.Business, "传入操作人员信息格式错误");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1001";
                retMsg.Message = "传入操作人员信息格式错误:" + ex.Message;
                return false;
            }
            if (string.IsNullOrEmpty(customerInfo))
            {
                WriteLogRecord(operators.Name, LogRecordTypeEnum.Business, "传入客人信息为空");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1002";
                retMsg.Message = "传入客人信息为空";
                return false;
            }
            try
            {
                customer = Newtonsoft.Json.JsonConvert.DeserializeObject<Customer>(customerInfo.Trim());
            }
            catch (Exception ex)
            {

                WriteLogRecord(operators.Name, LogRecordTypeEnum.Business, "传入客人信息格式错误");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1002";
                retMsg.Message = "传入客人信息格式错误:" + ex.Message;
                return false;
            }
            if (string.IsNullOrEmpty(roomInfo))
            {
                WriteLogRecord(operators.Name, LogRecordTypeEnum.Business, "传入客人信息为空");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1003";
                retMsg.Message = "传入房间信息为空";
                return false;
            }
            else if (roomInfo != "MakeVIPCard")
            {
                try
                {
                    room = Newtonsoft.Json.JsonConvert.DeserializeObject<Room>(roomInfo.Trim());
                }
                catch (Exception ex)
                {
                    WriteLogRecord(operators.Name, LogRecordTypeEnum.Business, "传入房间信息格式错误");
                    retMsg.IsSuccess = false;
                    retMsg.Status = "-1003";
                    retMsg.Message = "传入房间信息格式错误:" + ex.Message;
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 读取配置文件中Socket通讯的Ip地址以及端口
        /// </summary>
        /// <returns></returns>
        public bool GetSocketIpAndPort()
        {
            try
            {
                string file = System.Web.HttpContext.Current.Server.MapPath("ClientDevice.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(file);
                XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
                foreach (XmlElement element in topM)
                {
                    if (element.Name == "Device")
                    {
                        string house = element.Attributes["House"].Value;
                        if (house == "7")
                        {
                            socketIp = element.Attributes["IpAddress"].Value;
                            socketPort = element.Attributes["Port"].Value;
                        }

                    }
                }
                if (string.IsNullOrEmpty(socketIp.Trim()) || string.IsNullOrEmpty(socketPort.Trim()))
                {
                    WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "系统配置Ip地址和端口配置错误");
                    retMsg.IsSuccess = false;
                    retMsg.Status = "-1005";
                    retMsg.Message = "系统配置Ip地址和端口配置错误";
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                WriteLogRecord(operators.Name, LogRecordTypeEnum.System, "读取系统配置Ip地址和端口错误");
                retMsg.IsSuccess = false;
                retMsg.Status = "-1005";
                retMsg.Message = "读取系统配置Ip地址和端口错误";
                return false;
            }
        }

        /// <summary>
        /// 释放socket连接
        /// </summary>
        /// <param name="socket"></param>
        public void disposeSocket(Socket socket)
        {
            if (!socket.Connected)
            {
                //base.ReturnSuccessMessage("发送消息成功");
            }
            else
            {
                socket.Close();
                this.disposeSocket(socket);
            }
        }
    }
}
